//index.js
import store from '../../store/index'
import { hasKey, error, isUndefined, success, isEmpty } from '../../lib/js/utils'
import { updateUserContactWay, getUserContactWay } from '../../api/user'

// 创建页面
Page(
  store.createPage({
    /**
     * 提交表单
     */
    doSubmit: function() {
      const that = this
      const allContactWays = that.data.allContactWays
      allContactWays.forEach((item, index) => {
        if (!isEmpty(item.value)) {
          updateUserContactWay(item.id, item.value)
        }
      })
      that.doSubmitRefreshData()
    },
    /**
     * 提交表单后，刷新数据
     * @param {*} e
     */
    doSubmitRefreshData: function() {
      getUserContactWay().then(function(res) {
        store.dispatch('contactWays', res.data)
      })
    },
    /**
     * 修改联系方式设置data值
     */
    changeContactWay: function(e) {
      const that = this
      const value = e.detail.value
      const index = e.currentTarget.dataset.index
      var newContactWays = that.data.allContactWays
      newContactWays[index].value = value
      that.setData({
        contactWays: newContactWays
      })
    },
    /**
     * 初始化数据
     */
    initData: function() {
      const that = this
      const allContactWays = []
      that.data.allContactWays.forEach((item, index) => {
        that.data.contactWays.forEach(i => {
          if (item.id == i.contactType) {
            item.value = i.contactMark
          }
        })
        allContactWays.push(item)
      })
      console.log(allContactWays)
      that.setData({
        allContactWays: allContactWays
      })
    },

    data: {
      // 联系方式
      allContactWays: [
        {
          id: 1,
          name: 'QQ',
          value: ''
        },
        {
          id: 2,
          name: '微信',
          value: ''
        },
        {
          id: 3,
          name: '微博',
          value: ''
        }
      ]
    },
    globalData: ['userInfo', 'token', 'contactWays'],

    onLoad() {
      this.initData()
    }
  })
)
